package cn.tedu.charging.account.controller;

import cn.tedu.charging.account.dao.persist.mappers.PersonMapper;
import cn.tedu.charging.account.pojo.entity.Person;
import cn.tedu.charging.account.pojo.vo.UserLoginResultVO;
import cn.tedu.charging.account.pojo.vo.UserStandardVO;
import cn.tedu.charging.common.ex.ServiceException;
import cn.tedu.charging.common.po.UserLoginInfoPO;
import cn.tedu.charging.utils.JwtUtil;
import cn.tedu.charging.utils.WxCryptUtils;
import cn.tedu.charging.web.JsonResult;
import cn.tedu.charging.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/")
public class PersonController {
    @Autowired
    private PersonMapper mapper;

    @Value("${miniapp.wx.appId}")
    private String appId;

    @Value("${miniapp.wx.appSecret}")
    private String appSecret;

    @RequestMapping("test")
    public Object add() {
        QueryWrapper<Person> wrapper = new QueryWrapper<>();
        List<Person> list = mapper.selectList(wrapper);
        Object[] objects = list.toArray();
        Person person = new Person();
        person.setId(6L);
        person.setUsername("黄月英");
        person.setAge(18);
        Person[] people = {person};

        JsonResult jsonResult = new JsonResult();
        jsonResult.setState(200);
        jsonResult.setMessage("成功");
        jsonResult.setData(objects);
        return jsonResult;
    }


    @RequestMapping("loginTest")
    public Object loginTest(String code, String encryptData, String iv) throws Exception{
        // 1: 使用 code 换取  session_key、openid
        // 文档： https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
        StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?")
                .append("appid=" + this.appId)
                .append("&secret=" + this.appSecret)
                .append("&grant_type=authorization_code")
                .append("&js_code=" + code);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(requestUrl.toString(), HttpMethod.GET, new HttpEntity<String>(new HttpHeaders()), String.class);

        Map<String, String> body = (Map) JSON.parse(response.getBody());

        System.out.println(body);

        String sessionKey = body.get("session_key");
        String openid = body.get("openid");

        if (openid == null) {
            return "code无效，登陆失败";
        }

        // 调用 WxCryptUtils.decrypt(encryptData, iv, sessionKey); 解密用户信息
        try {
            String decrypt = WxCryptUtils.decrypt(sessionKey, iv, encryptData);
            Map<String, String> userInfo = (Map) JSON.parse(decrypt);

            System.out.println(userInfo.get("nickName"));

            return decrypt;
        } catch (Exception err) {
            return "获取用户信息失败";
        }
    }

//    @RequestMapping("loginTest1")
//    public Object loginTest1(String code, String encryptData, String iv) throws Exception{
//        StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?")
//                .append("appid=" + this.appId)
//                .append("&secret=" + this.appSecret)
//                .append("&grant_type=authorization_code")
//                .append("&js_code=" + code);
//
//        RestTemplate restTemplate = new RestTemplate();
//        ResponseEntity<String> response = restTemplate.exchange(requestUrl.toString(), HttpMethod.GET, new HttpEntity<String>(new HttpHeaders()), String.class);
//
//        Map<String, String> body = (Map) JSON.parse(response.getBody());
//        System.out.println(body);
//
//        String sessionKey = body.get("session_key");
//        String openId = body.get("openid");
//        if (openId == null) {
//            String message = "微信账号关联失败！";
//            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, message);
//        }
//        openId = userRepository.getOpenid(code, encryptData, iv)
//        String decrypt = WxCryptUtils.decrypt(sessionKey, iv, encryptData);
//        Map<String, Object> userInfo = (Map) JSON.parse(decrypt);
//        UserStandardVO userStandardVO = userRepository.selectByOpenId(openId);
//        if (userStandardVO != null){
//            userLoginResultVO = userService.login(openId);
//            return JsonResult.ok();
//        } else {
//            userLoginResultVO = userService.sign(userInfo, openId);
//            return JsonResult.ok();
//        }
//    }
}
